<?php
/**
 * +----------------------------------------------------------------------
 * | Copyright © Sogu Technologies Co. Ltd 2018-2050 All rights reserved.
 * +----------------------------------------------------------------------
 * | File name: helpers.php
 * +----------------------------------------------------------------------
 * | Author: sam
 * +----------------------------------------------------------------------
 * | Description: 自定义辅助函数
 * +----------------------------------------------------------------------
 * | Others: 其他内容的说明
 * +----------------------------------------------------------------------
 * | History: 修改历史记录列表，每条修改记录应包含修改日期、修改者及修改内容简述
 * +----------------------------------------------------------------------
 * | 1.Date: 2018/12/25 Author: sam Modification: 创建
 * +----------------------------------------------------------------------
 */
use Symfony\Component\HttpFoundation\Response;
use \Illuminate\Contracts\Pagination\LengthAwarePaginator;
if (! function_exists('stored')) {

    function stored($data, $message = '创建成功') {
        return respond($data, $message);
    }
}

if (! function_exists('updated')) {

    function updated($data, $message = '更新成功') {
        return respond($data, $message);
    }
}

if (! function_exists('deleted')) {

    function deleted($message = '删除成功') {
        return message($message);
    }
}


if (! function_exists('accepted')) {

    function accepted($message = '请求已接受，等待处理') {
        return message($message, Response::HTTP_ACCEPTED);
    }
}

if (! function_exists('notFound')) {

    function notFound($message = '您访问的资源不存在') {
        return message($message, Response::HTTP_NOT_FOUND,$header=[],$status_code=Response::HTTP_NOT_FOUND);
    }
}

if (! function_exists('internalError')) {

    function internalError($message = '未知错误导致请求失败', $code = Response::HTTP_INTERNAL_SERVER_ERROR) {
        return message($message, $code);
    }
}

if (! function_exists('failed')) {

    function failed($message, $code = Response::HTTP_BAD_REQUEST,$status_code =  Response::HTTP_OK) {
        return message($message, $code,$header=[],$status_code);
    }
}

if (! function_exists('success')) {

    function success($data,$header=[],$message='请求成功') {
        return respond($data, $message,$code = Response::HTTP_OK,$header);
    }
}

if (! function_exists('resp')) {

    function resp($data,$header=[],$message='请求成功') {
        return respData($data, $message,$code = Response::HTTP_OK,$header);
    }
}

if (! function_exists('message')) {

    function message($message, $code = Response::HTTP_OK,$header=[],$status_code=Response::HTTP_OK) {
        return respond([], $message, $code,$header,$status_code);
    }
}

if (! function_exists('respond')) {
    function respond($data = [], $message = '请求成功', $code = Response::HTTP_OK, array $header = [],$status_code=200) {
        if($data instanceof LengthAwarePaginator){
            return response()->json([
                'code' => $code,
                'msg' => $message,
                'time' => time(),
                'data' => [
                    'list'=>$data->items(),
                    'total'=>$data->total(),
                ],
            ], $status_code, $header)->setEncodingOptions(JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
        }
        return response()->json([
            'code' => $code,
            'msg' => $message,
            'time' => time(),
            'data' => $data ? $data: null,
        ], $status_code, $header)->setEncodingOptions(JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
    }
}

if(! function_exists('respData')){
    function respData($data = [], $message = '请求成功', $code = Response::HTTP_OK, array $header = [],$status_code=200) {
        return response()->json([
            'code' => $code,
            'msg'  => $message,
            'time' => time(),
            'data' => [
                'list'  => $data['data'],
                'total' => $data['total'],
            ],
        ], $status_code, $header)->setEncodingOptions(JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
    }
}


/**
 * 小黑鱼返回体
 * @param array $data
 * @param string $message
 * @param int $code
 * @param bool $success
 * @param array $header
 * @param int $status_code
 * @return \Illuminate\Http\JsonResponse
 * @author luwei
 * @date 2019-02-13 15:11
 */
if(! function_exists('fishResp')){
    function fishResp($data = [], $message = '请求成功', $code = Response::HTTP_OK, $success = true, array $header = [], $status_code=200) {
        $time = bcmul(bcsub(microtime(true), LARAVEL_START,3),1000);
        return response()->json([
            'success' => $success,
            'code' => $code,
            'msg'  => $message,
            'cost_time' => intval($time),
            'data' => $data,
        ], $status_code, $header)->setEncodingOptions(JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
    }
}

/**
 * 催收被调接口返回图
 */
if(! function_exists('collectionResp')){
    function collectionResp($data = [], $message = '请求成功', $code = Response::HTTP_OK, $success = true, array $header = [], $status_code=200) {
        \App\Models\CollectionApiRequest::createApiRequestData($data);
        $sign = '';
        if(!isset($data['obj'])){
            $data['obj'] = null;
        }
        $resultData = $data;
        return response()->json([
            'sign' => $sign,
            'resultData' => $resultData,
        ], $status_code, $header)->setEncodingOptions(JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
    }
}

if (! function_exists('getOssUrl')) {
    function getOssUrl($path = '', $timeout = 60*60*2) {
       //判断文件是否存在
        return Storage::disk('oss')->exists($path) ? (Storage::disk('oss')->signUrl($path, $timeout)) : '';
    }
}

/**
 * 手机验证码验证
 */
if (! function_exists('verifyPhoneCode')) {
    function verifyPhoneCode($phone,$code) {
        $verify_code = Cache::get($phone.'_code');
        return $verify_code == $code;
    }
}

/**
 * 返回两个时间相差天数
 * 2019-11-9  2019-11-7
 */
if (! function_exists('count_days')) {
    function count_days($now_time,$normal_time){
        $now_time = strtotime($now_time);
        $normal_time = strtotime($normal_time);
        $a_dt = getdate($now_time);
        $b_dt = getdate($normal_time);
        $a_new = mktime(12, 0, 0, $a_dt['mon'], $a_dt['mday'], $a_dt['year']);
        $b_new = mktime(12, 0, 0, $b_dt['mon'], $b_dt['mday'], $b_dt['year']);
        return round(($a_new-$b_new)/86400);
    }
}

if(! function_exists('getDayWithCh')){
    function  getDayWithCh($day)
    {
        $info = '';
        switch(\Carbon\Carbon::parse($day)->dayOfWeek){
            case 1:
                $info = '星期一';
                break;
            case 2:
                $info = '星期二';
                break;
            case 3:
                $info = '星球三';
                break;
            case 4:
                $info = '星期四';
                break;
            case 5:
                $info = '星期五';
                break;
            case 6:
                $info = '星球六';
                break;
            case 0 :
                $info = '星期天';
                break;
        }
        return $info;
    }
}

/**
 * 融360基础返回体
 */
if(!function_exists('r360Response')){
    function r360Response($message="",$data = [],$code=200,$http_code=Response::HTTP_OK){
        $resData = [
            "code"=>$code,
            "msg"=>"$message",
        ];
        if(!empty($data)){
            foreach ($data as $key => $value){
                $resData[$key] = $value;
            }
        }
        return response()->json($resData, $http_code)->setEncodingOptions(JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
    }
}

/**
 * 融360成功返回体
 */
if(!function_exists('r360success')){
    function r360Success($message="",$data = []){
        return r360Response($message,$data);
    }
}
/**
 * 融360失败返回体
 */
if(!function_exists('r360fail')){
    function r360fail($message="",$data = [],$code=400){
        return r360Response($message,$data,$code);
    }
}

/**
 * 13位时间戳
 * @param $data
 * @param $sign
 * @return int
 * @author shenzengguang
 * @date 2019-03-15 17:37
 */

if (!function_exists('microtime_float')){

    function microtime_float(){
        list($usec, $sec) = explode(" ", microtime());
        return ((float)$usec + (float)$sec);
    }
}


if (!function_exists('_sql')) {
    /**
     * 将此方法放在sql语句查询之前，可直接打印sql语句
     * @param int $sqlNo  1:打印单条sql，其他打印所有sql
     * @param string $method
     * @return bool
     */
    function _sql($sqlNo = 2, $method = 'log')
    {
        if (config('app.env') !== 'local' || config('app.debug') !== true) {
            return false;
        }

        \DB::listen(function($queryExcuted) use ($sqlNo, $method) {
            $sql = $queryExcuted->sql;
            $bindings = $queryExcuted->bindings;

            foreach ($bindings as $replace){
                $value = is_numeric($replace) ? $replace : "'".$replace."'";
                $sql = preg_replace('/\?/', $value, $sql, 1);
            }
            if (! is_numeric($sqlNo)) {
                $method = $sqlNo === 'dd' ? 'dd' : 'dump';
            }
            if ($method === 'log') {
                \Log::info($sql);
                if ($sqlNo === 1) {
                    die;
                }
            } else {
                $method($sql);
            }
        });
    }
}

